import re
import requests
import hashlib
import json
import os


# 翻译缓存字典
translation_cache = {}


def translate_and_replace_in_js(folder_path, app_id, secret_key):
    total_files = 0
    processed_files = 0

    for root, dirs, files in os.walk(folder_path):
        total_files += len(files)

    print(f"共发现 {total_files} 个JavaScript文件，开始处理...")

    for root, dirs, files in os.walk(folder_path):
        for js_file in files:
            if js_file.endswith(".js"):
                js_file_path = os.path.join(root, js_file)
                print(f"正在处理文件: {js_file_path} ({processed_files + 1}/{total_files})")
                processed_files += 1
                try:
                    with open(js_file_path, 'r', encoding='utf-8') as f:
                        js_content = f.read()

                    # 使用正则表达式匹配引号内的中文内容，单引号或双引号
                    chinese_pattern = re.compile(r"(['\"])([\u4e00-\u9fa5]+)\1")
                    chinese_matches = chinese_pattern.findall(js_content)

                    for match in chinese_matches:
                        chinese_text = match[1]
                        # 调用百度翻译API进行翻译
                        translation = translate_with_baidu(chinese_text, app_id, secret_key)
                        js_content = js_content.replace(match[0] + chinese_text + match[0], f"__('{translation}')")

                        # 获取当前处理的js文件名（去掉扩展名）作为字库文件名
                        module_name = os.path.splitext(js_file)[0]
                        append_to_wordbank(chinese_text, translation, module_name)

                    with open(js_file_path, 'w', encoding='utf-8') as f:
                        f.write(js_content)
                except FileNotFoundError as e:
                    print(f"文件未找到错误: {e}")
                except requests.exceptions.RequestException as e:
                    print(f"请求百度翻译API时出错: {e}")
                except Exception as e:
                    print(f"其他未知错误: {e}")

    print("所有文件处理完成！")


def translate_with_baidu(text, app_id, secret_key):
    if text in translation_cache:
        return translation_cache[text]

    url = "https://fanyi-api.baidu.com/api/trans/vip/translate"
    salt = "123456"  # 可自行使用一个随机盐值
    sign_str = f"{app_id}{text}{salt}{secret_key}"
    sign_str_encoded = sign_str.encode('utf-8')
    sign = hashlib.md5(sign_str_encoded).hexdigest()

    params = {
        "q": text,
        "from": "zh",
        "to": "en",
        "appid": app_id,
        "salt": salt,
        "sign": sign
    }

    try:
        response = requests.get(url, params=params)
        response.raise_for_status()

        # 检查API返回数据是否为空或格式错误
        if not response.text:
            print(f"百度翻译API返回空数据，文本: {text}")
            return None

        try:
            result = response.json()

            # 检查返回结果中是否存在'trans_result'键
            if "trans_result" in result:
                translation = result["trans_result"][0]["dst"]
                translation_cache[text] = translation
                return translation
            else:
                print(f"百度翻译API返回数据中不存在'trans_result'键，完整数据: {result}")
                return None
        except json.JSONDecodeError as e:
            print(f"百度翻译API返回数据格式错误，无法解析 JSON: {response.text}")
            return None
    except requests.exceptions.RequestException as e:
        print(f"请求百度翻译API时出错: {e}")
        return None


def append_to_wordbank(chinese_word, english_translation, module_name):
    wordbank_path = os.path.join("E:\\xufei\\translate-erp\\application\\admin\\lang\\zh-cn\\kuyou", f"{module_name}.php")

    if not os.path.exists(wordbank_path):
        # 如果文件不存在，创建新文件并写入初始内容
        with open(wordbank_path, 'w', encoding='utf-8') as file:
            file.write("<?php\nreturn [\n];")

    with open(wordbank_path, 'r', encoding='utf-8') as file:
        lines = file.readlines()

    new_entry = f"    '{english_translation}' => '{chinese_word}',\n"

    # 检查要追加的键值对是否已存在
    if not entry_exists(lines, new_entry):
        # 找到最后一个闭括号位置
        for i, line in enumerate(lines):
            if line.strip() == "];":
                lines.insert(i, new_entry)
                break
        # 如果没找到闭括号，说明字典为空，直接添加到文件开头
        else:
            lines.insert(0, new_entry)

    with open(wordbank_path, 'w', encoding='utf-8') as file:
        file.writelines(lines)


def entry_exists(lines, new_entry):
    for line in lines:
        if line.strip() == new_entry.strip():
            return True
    return False


if __name__ == "__main__":
    folder_path = "E:/xufei/translate-erp/application/admin/controller/kuyou"
    app_id = "20201112000614722"
    secret_key = "LiinO0W7NmmF6RHldPWX"

    translate_and_replace_in_js(folder_path, app_id, secret_key)